//引入插件，连接数据库、服务器
var express = require("express")
var app = express()
var bodyParser = require("body-parser")
app.use(bodyParser.json())
var mysql = require("mysql")
var cors = require('cors')
app.use(cors())
var client = mysql.createConnection({
    host: 'localhost',
    port: "3306",
    user: 'root',
    password: 'xurunle2001',
    database: 'zhihu'
})
client.connect(function (err) {
    if (err) throw err
    console.log("连接数据库成功")
})


app.listen(3200, function () {
  console.log("服务器连接成功");
})

//注册
app.post("/register", function (req, res) {
  let add = req.body
    client.query("select username from user where username=?", [add.username], function (err, results) {
        if (results[0] != null) {
            console.log(results);
            res.send('注册失败，用户名已存在')
        }
        else {
          add.follow = JSON.stringify(add.follow)
          add.collect = JSON.stringify(add.collect)
          add.browse = JSON.stringify(add.browse)
            client.query("insert into user values (null,?,?,?,?,?,?,?,?,?,?)",
                [add.username,add.password, add.Img, add.sex, add.follownum, add.collectnum, add.browsenum,add.collect ,add.follow,add.browse],
                function (err, results) {
                    if (results.affectedRows == 1) {
                        res.send("注册成功")
                    }
                })
        }
    })
})

//登录
app.post("/login", function (req, res) {
    let add = req.body
    client.query("select password from user where username=? ", [add.username], function (err, results) {
        if (results[0] != null && results[0].password == add.password) {
            res.send("登录成功")
        } else if (results[0] == null) {
            res.send("登陆失败，用户不存在，请前往注册");
        }else if (results[0] != null || results[0].password != add.password) {
            res.send("登陆失败，用户名或密码错误");
        }
    })
})

//获取头像
app.post("/getImg",function (req,res) {
    let add = req.body
    client.query("select Img from user where username=?",[add.username],function (err,results){
        res.send(results[0])
    })
})